package com.example.understand_compose1.testcase_activity

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.database.sqlite.SQLiteOpenHelper
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.understand_compose1.R
import com.example.understand_compose1.databinding.ActivityFetSqliteStoreDataBinding
import com.example.understand_compose1.fet_databaseusage.data.DatabaseHelper

// 插入，查询，更新，删除，
// BUG:但是id没有自增，为什么
class FetSqliteStoreDataActivity : AppCompatActivity() {
    lateinit var binding: ActivityFetSqliteStoreDataBinding

    lateinit var dbHelper: StudentDbHelper

    val thestudentdb = "students"
    // BUG: no such table: students

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityFetSqliteStoreDataBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        dbHelper = StudentDbHelper(this, thestudentdb, null, 1)
        dbHelper.writableDatabase
        binding.bt1.setOnClickListener { insertStudent() }
        binding.bt2.setOnClickListener { queryStudents() }
        binding.bt3.setOnClickListener { updateStudent() }
        binding.bt4.setOnClickListener { deleteStudent() }

    }

    private fun insertStudent() {
        val db = dbHelper.writableDatabase
        val values = ContentValues().apply {
            put("name", binding.et2.text.toString())
            put("age", binding.et1.text.toString())
        }

        val result = db.insert(thestudentdb, null, values)
        if (result != -1L) {
            Toast.makeText(this, "插入数据成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "插入数据失败", Toast.LENGTH_SHORT).show()
        }

        db.close()
    }

    private fun queryStudents() {
        val db = dbHelper.readableDatabase
        val cursor = db.query(thestudentdb, null, null, null, null, null, null)

        val result = StringBuilder()
        with(cursor) {
            while (moveToNext()) {
                val id = getInt(getColumnIndexOrThrow("_id"))
                val name = getString(getColumnIndexOrThrow("name"))
                val age = getInt(getColumnIndexOrThrow("age"))
                result.append("_id: $id, Name: $name, Age: $age\n")
            }
        }
        binding.tv3.text = result.toString()
        cursor.close()
        db.close()
    }
    // TODO: 这里奇怪，id一直是0
    private fun updateStudent() {
        val db = dbHelper.writableDatabase
        val values = ContentValues().apply {
            put("age", binding.et1.text.toString().toIntOrNull() ?: 0)
            put("name", binding.et2.text.toString())
        }
        val whereClause = "_id = ?"
        val whereArgs = arrayOf(binding.et3.text.toString())
        val affectedRows = db.update(thestudentdb, values, whereClause, whereArgs)
        Toast.makeText(this, "更新了 $affectedRows 行数据", Toast.LENGTH_SHORT).show()
        db.close()
    }

    private fun deleteStudent() {
        val db = dbHelper.writableDatabase
        val whereClause = "name=?"
        val whereArgs = arrayOf(binding.et2.text.toString())

        val result = db.delete(thestudentdb, whereClause, whereArgs)
        if (result > 0) {
            Toast.makeText(this, "删除数据成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "删除数据失败", Toast.LENGTH_SHORT).show()
        }

        db.close()
    }

    override fun onDestroy() {
        dbHelper.close()
        super.onDestroy()
    }
}


class StudentDbHelper(
    ctx: Context,
    name: String,
    factory: CursorFactory?,
    version: Int
) : SQLiteOpenHelper(ctx, name, factory, version) {
    override fun onCreate(db: SQLiteDatabase?) {
        Log.d("Feature: 创建sqlite数据库", "onCreate: 创建数据库表")
        // Student表
        // id int
        // name varchar
        // age int
        val drop_sql = "DROP TABLE IF EXISTS students";
        db?.execSQL(drop_sql)
        // TODO: 这里建表有问题吗？
        val create_table_sql =
            "create table students (_id integer primary key autoincrement, name varchar, age integer)"
        assert(db != null)
        db?.execSQL(create_table_sql)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        Log.d("Feature: 升级sqlite数据库", "onUpgrade: 升级数据库")
        // 例如，修改student表结构
        val modify_table_sql = "alter table student add phone integer"
        db?.execSQL(modify_table_sql)
    }
}

/*
package com.example.understand_compose1.testcase_activity

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.database.sqlite.SQLiteOpenHelper
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.understand_compose1.R
import com.example.understand_compose1.databinding.ActivityFetSqliteStoreDataBinding

class FetSqliteStoreDataActivity : AppCompatActivity() {
    lateinit var binding: ActivityFetSqliteStoreDataBinding
    lateinit var dbHelper: StudentDbHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityFetSqliteStoreDataBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化数据库帮助类
        dbHelper = StudentDbHelper(this, "student.sqlite", null, 1)

        // 设置按钮点击监听器
        binding.btnInsert.setOnClickListener { insertStudent() }
        binding.btnQuery.setOnClickListener { queryStudents() }
        binding.btnUpdate.setOnClickListener { updateStudent() }
        binding.btnDelete.setOnClickListener { deleteStudent() }
    }

    // 插入学生数据
    private fun insertStudent() {
        val db = dbHelper.writableDatabase
        val values = ContentValues().apply {
            put("name", binding.etName.text.toString())
            put("age", binding.etAge.text.toString().toIntOrNull() ?: 0)
        }
        val result = db.insert("student", null, values)
        if (result != -1L) {
            Toast.makeText(this, "插入成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "插入失败", Toast.LENGTH_SHORT).show()
        }
        db.close()
    }

    // 查询所有学生
    private fun queryStudents() {
        val db = dbHelper.readableDatabase
        val cursor = db.query("student", null, null, null, null, null, null)
        val result = StringBuilder()
        with(cursor) {
            while (moveToNext()) {
                val id = getInt(getColumnIndexOrThrow("_id"))
                val name = getString(getColumnIndexOrThrow("name"))
                val age = getInt(getColumnIndexOrThrow("age"))
                result.append("ID: $id, 姓名: $name, 年龄: $age\n")
            }
        }
        binding.tvResult.text = result.toString()
        cursor.close()
        db.close()
    }

    // 更新学生数据
    private fun updateStudent() {
        val db = dbHelper.writableDatabase
        val values = ContentValues().apply {
            put("age", binding.etAge.text.toString().toIntOrNull() ?: 0)
        }
        val whereClause = "name = ?"
        val whereArgs = arrayOf(binding.etName.text.toString())
        val affectedRows = db.update("student", values, whereClause, whereArgs)
        Toast.makeText(this, "更新了 $affectedRows 行数据", Toast.LENGTH_SHORT).show()
        db.close()
    }

    // 删除学生数据
    private fun deleteStudent() {
        val db = dbHelper.writableDatabase
        val whereClause = "name = ?"
        val whereArgs = arrayOf(binding.etName.text.toString())
        val affectedRows = db.delete("student", whereClause, whereArgs)
        Toast.makeText(this, "删除了 $affectedRows 行数据", Toast.LENGTH_SHORT).show()
        db.close()
    }
}

class StudentDbHelper(
    ctx: Context,
    name: String,
    factory: CursorFactory?,
    version: Int
) : SQLiteOpenHelper(ctx, name, factory, version) {
    override fun onCreate(db: SQLiteDatabase?) {
        Log.d("Feature: 创建sqlite数据库", "onCreate: 创建数据库表")
        // 创建学生表
        val createTableSql = "CREATE TABLE student (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"
        db?.execSQL(createTableSql)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        Log.d("Feature: 升级sqlite数据库", "onUpgrade: 升级数据库")
        // 如果需要升级数据库结构，可以在这里添加逻辑
    }
}
 */


/*
当然可以。以下是对所选代码 `enableEdgeToEdge()` 的中文解释：

`enableEdgeToEdge()` 是一个函数调用，用于为活动（Activity）启用边缘到边缘的显示。以下是它的功能解释：

1. 目的：这个函数用于使应用的内容延伸到屏幕的边缘，包括通常保留给系统UI元素（如状态栏和导航栏）的区域。

2. 视觉效果：它允许您的应用内容显示在透明的系统栏后面，创造一种更加沉浸式的用户体验。

3. Jetpack的一部分：这个函数是AndroidX Core库的一部分，而AndroidX Core库是Jetpack套件的组成部分。Jetpack是一套帮助开发者遵循最佳实践并减少样板代码的库。

4. 使用时机：它通常在活动生命周期的早期被调用，通常是在`onCreate()`方法中设置内容视图之前。

5. 兼容性：这个函数设计用于在不同的Android版本上工作，在支持的设备上提供一致的边缘到边缘的体验。

6. 额外设置：调用此函数后，您通常需要手动处理窗口插图（window insets），以确保您的UI元素不会与系统栏重叠。这就是为什么您在代码的后面看到设置了`setOnApplyWindowInsetsListener`。

7. 性能：启用边缘到边缘显示可能会通过减少绘制UI所需的布局传递次数来提高性能。

通过使用`enableEdgeToEdge()`，您选择了一种更现代、更沉浸式的UI设计，充分利用了设备上可用的全屏空间。
 */